import * as THREE from 'three'

import {GLTFLoader} from 'three/examples/jsm/loaders/GLTFLoader.js';
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js'
import{FBXLoader} from 'three/examples/jsm/loaders/FBXLoader'
import { CSS3DObject } from 'three/examples/jsm/renderers/css3drenderer';
import $ from 'jquery';
import { dataListStore } from '../../stores/dataList';
import { GUI } from 'three/examples/jsm/libs/lil-gui.module.min';
import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader';

const store = dataListStore();
let className = store.classNames;
const stateName = store.stateName; 
export function loaderModel(data,scene,modelLcGroup,labelGroup,css3dLabelGroup,css3dLabelXQGroup) {
    let url = "static/OnePart.glb"
    const loader = new GLTFLoader();
    const dracoLoader = new DRACOLoader();
    dracoLoader.setDecoderPath( 'static/draco/');
    loader.setDRACOLoader(dracoLoader);
    const hdrEquirect = new RGBELoader().setPath( 'static/hdr/' ).load( 'hdr_E.hdr', function (texture) {
        hdrEquirect.mapping = THREE.EquirectangularReflectionMapping;
        ///scene.background = texture;
        scene.environment = texture;
    } );

    loader.load(url, (gltf) => {
        let gltfs = gltf.scene;
        //console.log(gltfs);
        gltfs.traverse(function (child) {
            let item = child.clone();
            if (item instanceof THREE.Mesh) {
                item.name = item.name.replaceAll("_", '-');
                item.material.metalness= 1.0;
                item.material.roughness= 0.2;
				
               // console.log(item, item.position);
                if (item.name == 'A1-1') {
                    item.visible = false;
                    // createLabel(item, data,item.name, css3dLabelGroup);
                    css3dLabelXQ(item, data, item.name, css3dLabelXQGroup);
                    labelGroup.add(item)
                } else if (item.name == 'hd-11') { 
                    // let itemTop = child.clone();
                    // itemTop.material = child.material.clone();
                    // itemTop.name = 'hd-11-top';
                    // modelLcGroup.add(itemTop);
                    
                    item.userData.size = getSizeFn( item );
                    item.userData.position = {
                        x: item.position.x,
                        y: item.position.y,
                        z: item.position.z
                    };
                    item.userData.scale = {
                        x: item.scale.x,
                        y: item.scale.y,
                        z: item.scale.z
                    };
                    // item.material.userData.initH = item.position.y - 3.8610129;
                    // item.material.clipIntersection = true;
                    // let plan = new THREE.Plane( new THREE.Vector3( 0, -1, 0 ), item.material.userData.initH );
                    // item.material.clippingPlanes = [ plan ];

                    // var helpers = new THREE.Group();
                    // helpers.add( new THREE.PlaneHelper( plan, 50, 0xDC143C ) );
                    // scene.add(helpers);

                    //item.material.reflectivity = 1 
                    modelLcGroup.add(item);
                    
                } else {
                    scene.add(item)
                }
               // console.log(item);
                //scene.add(item)
            }
        })
        //scene.add(gltfs)
    })
}
export function fbxLoaderModel(data,scene,modelLcGroup,labelGroup,css3dLabelGroup,css3dLabelXQGroup) {
     let url = "static/AAA.FBX"
    const loader = new FBXLoader();
    loader.load(url, (fbx) => {
        fbx.traverse(function (child) { 
            let item = child.clone();
			
            if (item instanceof THREE.Mesh) { 
                item.name = item.name.replaceAll("_", '-');
                if (item.name == 'A1-1') {
                    item.visible = false;
                    createLabel(item, data,item.name, css3dLabelGroup);
                    css3dLabelXQ(item,data, item.name, css3dLabelXQGroup);
                    labelGroup.add(item);
                } else if (item.name == 'hd-11-hz') {
                    item.material =  new THREE.MeshBasicMaterial({
                        color: 0x66ccff,
                        transparent: true,
                        opacity: 0.36,
                        depthTest: false,
                        depthWrite: true,
                        side:THREE.FrontSide
                    })
                     let edges = new THREE.EdgesGeometry(item.geometry);
					let linemodel = new THREE.LineSegments(
						edges, new THREE.LineBasicMaterial({
							color: '#3328c8',
							transparent: true,
							opacity: 1
						})
					)
                    linemodel.name = item.name + "-Line";
                    linemodel.position.copy(item.position);
                    let axis = new THREE.Vector3(1,0,0);
                     linemodel.rotateOnAxis(axis,-Math.PI/2);
                    scene.add(linemodel)
                    scene.add(item)
                } else if (item.name == 'hd-11') {
                    //  item.material.map((i,index) => {
                    //     if (i.name == 'gray_01') {
                    //         item.material[index] = new THREE.MeshLambertMaterial({
                    //             color: 0x4E4E4E,
                    //             name:'gray_01'
                    //         })
                    //     }
                    //  })
                    item.userData.size = getSizeFn( item );
                    item.userData.position = {
                        x: item.position.x,
                        y: item.position.y,
                        z: item.position.z
                    };
                    item.userData.scale = {
                        x: item.scale.x,
                        y: item.scale.y,
                        z: item.scale.z
                    };
                    item.material.clipIntersection = true;

                    item.material.clippingPlanes = [ new THREE.Plane( new THREE.Vector3( 0, - 1, 0 ), item.position.y + 10 ) ];
                    modelLcGroup.add(item);
                    let itemTop = item.clone();
                    itemTop.name = 'hd-11-top';
                    modelLcGroup.add(itemTop);
                    
                } else if(item.name == 'hd-11-1') {
                    let edges = new THREE.EdgesGeometry(item.geometry);
                    let linemodel = new THREE.LineSegments(
                        edges, new THREE.LineBasicMaterial({
                            color: '#3328c8',
                            transparent: true,
                            opacity: 1
                        })
                    )
                    linemodel.name = item.name+"-Line";
                    linemodel.position.copy(item.position);
                    let axis = new THREE.Vector3(1,0,0);
                    linemodel.rotateOnAxis(axis,-Math.PI/2);
                    scene.add(linemodel)
                    scene.add(item)
                } else {
                    scene.add(item)
                }
                //scene.add(item)
            }
        })
    })
}


function getSizeFn( mesh ){
    let box = new THREE.Box3();
    box.setFromObject( mesh );
    let size = new THREE.Vector3();
    box.getSize( size );
    return{
        width: Number( size.x ).toFixed(2),
        height: Number( size.y ).toFixed(2),
        depth: Number( size.z ).toFixed(2)
    }
   // console.log( "Width: " + size.x + ", Height: " + size.y + ", Depth: " + size.z );
}
function createLabel(item, datas,label, css3dLabelGroup) {
    let data = JSON.stringify(datas);
    let html = `<div class="labelTitles_realtime ${className[datas.state]} ${label}" id="oneLabelTitles">
        <span>${label}</span>
    </div>`;
    let css3dLabel = new CSS3DObject($(html)[0]);
    css3dLabel.position.x = item.position.x;
    css3dLabel.position.y = item.position.y+80;
    css3dLabel.position.z = item.position.z;
    css3dLabel.name = label;
    css3dLabel.scale.set(5, 5, 5);
    css3dLabel.rotateY( Math.PI );
    css3dLabelGroup.add(css3dLabel);
}
function css3dLabelXQ(item,datas, label, css3dLabelXQGroup) {
    let data = JSON.stringify(datas);
    let wz = "除尘器A侧右室";
    if (datas.hopper.indexOf('A1-') != -1 || datas.hopper.indexOf('A2-') != -1) {
        wz = '除尘器A侧右室'
    } else if (datas.hopper.indexOf('A3-') != -1 || datas.hopper.indexOf('A4-') != -1) {
        wz = '除尘器A侧左室'
    }else if (datas.hopper.indexOf('B1-') != -1 || datas.hopper.indexOf('B2-') != -1) {
        wz = '除尘器B侧右室'
    }else if (datas.hopper.indexOf('B3-') != -1 || datas.hopper.indexOf('B4-') != -1) {
        wz = '除尘器B侧左室'
    }
    let html = `<div class="labelXq_realtime" id="oneLabelXq">
                <div class="top ${className[datas.state]}">
                <div class="title"><span>${wz}</span>
                    <div class="closeIcon" ></div>
                </div>
                <div class="center">
                    <div class="name centerCenter">
                        <span class="labelTitle">灰斗名称：</span>
                        <span class="labelNr labelNrMc">${label}</span>
                    </div>
                    <div class="hw centerCenter">
                        <span class="labelTitle">灰位：</span>
                        <span class="labelNr labelNrHw ${className[datas.state]}">${datas.height.toFixed(2)}米</span>
                    </div>
                    <div class="bjzt centerCenter">
                        <span class="labelTitle">报警状态：</span>
                        <span class="labelNr labelNrZt ${className[datas.state]}">${stateName[datas.state]}</span>
                    </div>
                    <div class="bjzt centerCenter flex-press-one">
                        <div class="labelTitle">灰荷载：</div>
                        <div class="labelNr labelNrHzai ${className[datas.state]}">
                            <div class="in-press"></div>
                        </div>
                        <span class="${className[datas.state]}">${(datas.load_rate.toFixed(4) * 100).toFixed(2)} %</span>
                    </div>
                </div>
            </div>
            <div class="bottom ${className[datas.state]} ${label}">

            </div>
    </div>`;
    let css3dLabel = new CSS3DObject($(html)[0]);
    css3dLabel.position.x = item.position.x;
    css3dLabel.position.y = item.position.y+8;
    css3dLabel.position.z = item.position.z;
    css3dLabel.name = label;
    css3dLabel.scale.set(0.17, 0.17, 0.17);
    css3dLabel.rotateY(Math.PI+Math.PI/11);
    //css3dLabel.visible = false;
    // if (datas.state == 2 || datas.state == 3) {
    //     css3dLabel.visible = true;
    // }
    css3dLabelXQGroup.add(css3dLabel);
}